package com.dongjiantong.openplatform.core;/**
 * Created by cao on 2017/12/13.
 */

import com.dongjiantong.openplatform.entity.OPResponse;
import com.dongjiantong.openplatform.exceptions.OPException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.net.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author cao
 * @create 2017-12-13 下午8:26
 **/

@ControllerAdvice
public class OPExceptionHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired(
            required = false
    )
    private OPMessageSource messageSource;
    @Autowired
    private OpenProperties properties;

    public OPExceptionHandler() {
    }

    @ExceptionHandler({OPException.class})
    public void OPErrorHandler(OPException e, HttpServletResponse response) throws Exception {
        response.setContentType(MediaType.JSON_UTF_8.toString());
        response.setStatus(e.getStatus());
        PrintWriter out = response.getWriter();
        Throwable var4 = null;

        try {
            out.print(this.objectMapper.writeValueAsString(OPResponse.fail(e.getReason(), this.get(e.getReason(), e.getArgs()))));
        } catch (Throwable var13) {
            var4 = var13;
            throw var13;
        } finally {
            if(out != null) {
                if(var4 != null) {
                    try {
                        out.close();
                    } catch (Throwable var12) {
                        var4.addSuppressed(var12);
                    }
                } else {
                    out.close();
                }
            }

        }

    }

    private String get(String code, Object... args) {
        if(this.messageSource != null && StringUtils.hasText(code)) {
            if(this.properties.isDebug()) {
                String expected = this.messageSource.get("debug." + code, args);
                if(StringUtils.hasText(expected) && !expected.equals("debug." + code)) {
                    return expected;
                }
            }

            return this.messageSource.get(code, args);
        } else {
            return "";
        }
    }
}
